#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <netdb.h>

#define BUF_SIZE 500

int main(int argc, char *argv[])
{
	struct addrinfo hints;
    struct addrinfo *result = NULL, *rp = NULL;
    int sfd, s;
    struct sockaddr_storage peer_addr;
    socklen_t peer_addr_len;
    ssize_t nread;
    char buf[BUF_SIZE];

    if (argc != 2) {
        fprintf(stderr, "Usage: %s port\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    memset(&hints, 0, sizeof(struct addrinfo));
    hints.ai_family     = AF_UNSPEC;     /* Allow IPv4 or IPv6 */
    hints.ai_socktype   = SOCK_STREAM;  /* Datagram socket */
    hints.ai_flags      = AI_ADDRCONFIG;
    //hints.ai_protocol   = 0;          /* Any protocol */
    hints.ai_protocol   = IPPROTO_TCP; 
    hints.ai_canonname  = NULL;
    hints.ai_addr       = NULL;
    hints.ai_next       = NULL;

    //s = getaddrinfo("172.16.133.133", argv[1], &hints, &result);
    //s = getaddrinfo("127.0.0.0", argv[1], &hints, &result);
    s = getaddrinfo("0.0.0.0", argv[1], &hints, &result);
    if (s != 0) {
        fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
        exit(EXIT_FAILURE);
    }

    /* getaddrinfo() returns a list of address structures.
       Try each address until we successfully bind(2).
       If socket(2) (or bind(2)) fails, we (close the socket
       and) try the next address. */

    for (rp = result; rp != NULL; rp = rp->ai_next) {
        char host[NI_MAXHOST] = {0};
        char port[NI_MAXSERV] = {0};
        getnameinfo(rp->ai_addr,NI_MAXHOST,host,NI_MAXHOST,port,NI_MAXSERV,NI_NUMERICHOST|NI_NUMERICSERV);
        printf("addr,%s:%s\n",host,port);
    }

    freeaddrinfo(result);           /* No longer needed */
    return 0;
}
